package com.mgq.template.batch;

import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <b>功能：</b>分批执行<br>
 * <b>Copyright mgq</b>
 * <li>版本&nbsp;&nbsp;&nbsp;&nbsp;修改日期&nbsp;&nbsp;&nbsp;&nbsp;部　　门&nbsp;&nbsp;&nbsp;&nbsp;作　者&nbsp;&nbsp;&nbsp;&nbsp;变更内容</li><hr>
 * <li>v1.0&nbsp;&nbsp;&nbsp;&nbsp;20220412&nbsp;&nbsp;营业后台&nbsp;&nbsp;&nbsp;&nbsp;马广奇&nbsp;&nbsp;&nbsp;&nbsp;创建类</li>
 * <br><br>
 *
 * @author 马广奇
 * @version 2022-04-12 19:08
 */
public class ExecuteBatch {
    /**
     * 分批执行的写法(每1000提交一次) 批量执行
     */
    public static <T> void batch(Collection<T> list, int batchSize, Consumer<T> consumer) {
        // List<Integer> list =  IntStream.rangeClosed(1,2005).boxed().collect(Collectors.toList());
        int size = list.size();
        int idxLimit = Math.min(batchSize, size);
        int i = 1;
        for (T element : list) {
            if (i == idxLimit) {
                consumer.accept(element);
                idxLimit = Math.min(idxLimit + batchSize, size);
            }
            i++;
        }
    }

    public static void main(String[] args) {
        List<Integer> list = IntStream.rangeClosed(1, 2005).boxed().collect(Collectors.toList());
        batch(list, 1000, System.out::println);


    }
}
